package com.javaee.interceptor.Utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//对cookie进行增删改查
public class ManagerCookies {
    public static void Createcookies(HttpServletRequest request, HttpServletResponse
            response,String cookieName,String cookieValue) throws UnsupportedEncodingException {
        Cookie cookie=new Cookie(cookieName, URLEncoder.encode(cookieValue, "utf-8"));
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);//存活时常为一个月
        response.addCookie(cookie);
    }
    public static void Updatecookies(HttpServletRequest request, HttpServletResponse
            response,String cookieName,String newcookieValue) throws UnsupportedEncodingException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                cookie.setValue(newcookieValue);
                response.addCookie(cookie);
                break;
            }
        }
    }
    public static void Deletecookies(HttpServletRequest request, HttpServletResponse
            response,String cookieName) throws UnsupportedEncodingException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                cookie.setValue(null);
                response.addCookie(cookie);
                break;
            }
        }
    }
}
